import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/investment_data.dart';
import '../services/investment_service.dart';
import '../widgets/investment_overview_card.dart';
import '../widgets/asset_breakdown_chart.dart';
import '../widgets/recommendation_list.dart';
import '../widgets/loading_indicator.dart';
import '../widgets/error_widget.dart';

class InvestorCenterScreen extends StatefulWidget {
  const InvestorCenterScreen({super.key});

  @override
  State<InvestorCenterScreen> createState() => _InvestorCenterScreenState();
}

class _InvestorCenterScreenState extends State<InvestorCenterScreen> {
  late final InvestmentService _investmentService;
  late Future<AssetOverview> _assetOverviewFuture;
  late Future<InvestmentAnalysis> _investmentAnalysisFuture;
  late Future<PersonalizedRecommendation> _recommendationsFuture;

  @override
  void initState() {
    super.initState();
    _investmentService = InvestmentService();
    _loadData();
  }

  void _loadData() {
    setState(() {
      _assetOverviewFuture = _investmentService.getMockAssetOverview();
      _investmentAnalysisFuture = _investmentService.getMockInvestmentAnalysis();
      _recommendationsFuture = _investmentService.getMockPersonalizedRecommendations();
    });
  }

  Future<void> _refreshData() async {
    _loadData();
    await Future.wait([
      _assetOverviewFuture,
      _investmentAnalysisFuture,
      _recommendationsFuture,
    ]);
  }

  @override
  void dispose() {
    _investmentService.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('投资者中心'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _refreshData,
            tooltip: '刷新数据',
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: _refreshData,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildHeaderSection(),
              const SizedBox(height: 20),
              _buildOverviewSection(),
              const SizedBox(height: 20),
              _buildAnalysisSection(),
              const SizedBox(height: 20),
              _buildRecommendationsSection(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeaderSection() {
    return const Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '欢迎来到投资者中心',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 8),
        Text(
          '管理您的数字资产，获取个性化投资建议',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  Widget _buildOverviewSection() {
    return FutureBuilder<AssetOverview>(
      future: _assetOverviewFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const LoadingIndicator();
        }

        if (snapshot.hasError) {
          return ErrorWidgetCustom(
            error: snapshot.error.toString(),
            onRetry: _refreshData,
          );
        }

        final overview = snapshot.data!;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '资产总览',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            InvestmentOverviewCard(overview: overview),
            const SizedBox(height: 16),
            AssetBreakdownChart(overview: overview),
          ],
        );
      },
    );
  }

  Widget _buildAnalysisSection() {
    return FutureBuilder<InvestmentAnalysis>(
      future: _investmentAnalysisFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const LoadingIndicator();
        }

        if (snapshot.hasError) {
          return ErrorWidgetCustom(
            error: snapshot.error.toString(),
            onRetry: _refreshData,
          );
        }

        final analysis = snapshot.data!;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '投资分析',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildAnalysisCards(analysis),
            const SizedBox(height: 16),
            _buildPerformanceChart(analysis),
          ],
        );
      },
    );
  }

  Widget _buildAnalysisCards(InvestmentAnalysis analysis) {
    return GridView.count(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisCount: 2,
      crossAxisSpacing: 12,
      mainAxisSpacing: 12,
      childAspectRatio: 1.5,
      children: [
        _buildAnalysisCard(
          '总回报率',
          '${analysis.totalReturn.toStringAsFixed(1)}%',
          analysis.totalReturn >= 0 ? Colors.green : Colors.red,
          Icons.trending_up,
        ),
        _buildAnalysisCard(
          '年化收益',
          '${analysis.annualizedReturn.toStringAsFixed(1)}%',
          analysis.annualizedReturn >= 0 ? Colors.green : Colors.red,
          Icons.show_chart,
        ),
        _buildAnalysisCard(
          '波动率',
          '${analysis.volatility.toStringAsFixed(1)}%',
          Colors.orange,
          Icons.waves,
        ),
        _buildAnalysisCard(
          '夏普比率',
          analysis.sharpeRatio.toStringAsFixed(2),
          Colors.blue,
          Icons.analytics,
        ),
      ],
    );
  }

  Widget _buildAnalysisCard(
    String title,
    String value,
    Color color,
    IconData icon,
  ) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: 8),
            Text(
              value,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: color,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              title,
              style: const TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPerformanceChart(InvestmentAnalysis analysis) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '历史表现',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            Container(
              height: 200,
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Center(
                child: Text(
                  '图表组件待实现',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontStyle: FontStyle.italic,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRecommendationsSection() {
    return FutureBuilder<PersonalizedRecommendation>(
      future: _recommendationsFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const LoadingIndicator();
        }

        if (snapshot.hasError) {
          return ErrorWidgetCustom(
            error: snapshot.error.toString(),
            onRetry: _refreshData,
          );
        }

        final recommendations = snapshot.data!;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '个性化推荐',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            RecommendationList(recommendations: recommendations),
          ],
        );
      },
    );
  }
}